<template>
  <div class="component_container">
    <!-- 提交周报列表组件 -->
    <div class="report_cell_title" :style="{ 'background-color': titleBg }">
      <span>上个工作日完成</span>
      <div>
        <span v-if="reportData.lastFinishReportList.length" class="time_text">
          {{ reportData.lastFinishReportList[0].reportTime }}
        </span>
        <el-button
          v-if="createBtnVisible"
          style="margin-left: 15px"
          size="mini"
          type="warning"
          plain
          @click="createReport('lastFinishReportList')"
        >
          添加
        </el-button>
      </div>
    </div>

    <!-- <vxe-table
                  v-if="reportData.lastFinishReportList.length"
                  :data="reportData.lastFinishReportList"
                  :show-header="false"
                  :span-method="mergeRowMethod"
                  align="center"
                >
                  <vxe-column type="seq" title="序号" width="42"></vxe-column>

                  <vxe-column
                    title="模块名称"
                    field="moduleNames"
                    align="left"
                    header-align="center"
                  >
                    <template #default="{ row }">
                      <span v-for="(cell, j) in row.moduleNamesArr" :key="j">
                        【{{ cell }}】
                      </span>
                    </template>
                  </vxe-column>

                  <vxe-column
                    field="reportText"
                    title="工作内容"
                    min-width="300"
                    align="left"
                    header-align="center"
                  ></vxe-column>

                  <vxe-column title="工作进度" width="100">
                    <template #default="{ row }">
                      <div v-if="Number(row.workProgress)">
                        {{ row.workProgress }} %
                      </div>
                    </template>
                  </vxe-column>

                  <vxe-column
                    field="reportName"
                    title="报告人"
                    width="100"
                  ></vxe-column>
                </vxe-table> -->

    <div v-if="reportData.lastFinishReportList.length">
      <div
        v-for="(val, key) in lastFinishReportObj"
        :key="key"
        class="report_content_part"
      >
        <div class="report_part_title">{{ key }}</div>

        <div class="report_cell_content">
          <!-- trigger="click" -->
          <el-tooltip
            v-for="(item, i) in val"
            :key="i"
            placement="right-start"
            :disabled="!deleteBtnVisible"
          >
            <template #content>
              <div class="report_commit_list_cell_control_box">
                <div class="btn">
                  <edit
                    @click="editReportItem(item, 'lastFinishReportList')"
                    class="icon"
                  />
                </div>
                <span class="split_char"></span>
                <div class="btn">
                  <delete
                    @click="deleteReportItem(item, 'lastFinishReportList')"
                    class="icon"
                  />
                </div>
              </div>
            </template>
            <div class="report_cell_item">
              <span class="nowrap">{{ i + 1 }}、</span>
              <div class="f_1">
                <span>{{ item.reportText }}</span>
                <span v-if="Number(item.workProgress)" class="nowrap ml_s">
                  {{ item.workProgress }}%
                </span>
                <span class="nowrap ml_s"> —— {{ item.reportName }} </span>
              </div>
              <!-- <div
                v-if="deleteBtnVisible"
                class="delete_btn"
                @click="deleteReportItem(item, 'last')"
              >
                <delete-filled
                  style="
                    width: 1.2em;
                    height: 1.2em;
                    margin-right: 14px;
                    color: #f56c6c;
                  "
                />
              </div> -->
            </div>
          </el-tooltip>
        </div>
      </div>
    </div>
    <div v-else class="empty_box">无</div>

    <div class="report_cell_title" :style="{ 'background-color': titleBg }">
      <span>今日工作计划</span>
      <div>
        <span v-if="reportData.todayPlanReportList.length" class="time_text">
          {{ reportData.todayPlanReportList[0].reportTime }}
        </span>
        <el-button
          v-if="createBtnVisible"
          style="margin-left: 15px"
          size="mini"
          type="warning"
          plain
          @click="createReport('todayPlanReportList')"
        >
          添加
        </el-button>
      </div>
    </div>

    <!-- <vxe-table
                  :data="reportData.todayPlanReportList"
                  :show-header="false"
                  :span-method="mergeRowMethod"
                  align="center"
                >
                  <vxe-column type="seq" title="序号" width="42"></vxe-column>

                  <vxe-column
                    title="模块名称"
                    field="moduleNames"
                    align="left"
                    header-align="center"
                  >
                    <template #default="{ row }">
                      <span v-for="(cell, j) in row.moduleNamesArr" :key="j">
                        【{{ cell }}】
                      </span>
                    </template>
                  </vxe-column>

                  <vxe-column
                    field="reportText"
                    title="工作内容"
                    min-width="300"
                    align="left"
                    header-align="center"
                  ></vxe-column>

                  <vxe-column title="工作进度" width="100">
                    <template #default="{ row }">
                      <div v-if="Number(row.workProgress)">
                        {{ row.workProgress }} %
                      </div>
                    </template>
                  </vxe-column>

                  <vxe-column
                    field="reportName"
                    title="报告人"
                    width="100"
                  ></vxe-column>
                </vxe-table> -->

    <div v-if="reportData.todayPlanReportList.length">
      <div
        v-for="(val, key) in todayPlanReportObj"
        :key="key"
        class="report_content_part"
      >
        <div class="report_part_title">
          {{ key }}
        </div>

        <div class="report_cell_content">
          <!-- trigger="click" -->
          <el-tooltip
            v-for="(item, i) in val"
            :key="i"
            placement="right-start"
            :disabled="!deleteBtnVisible"
          >
            <template #content>
              <div class="report_commit_list_cell_control_box">
                <div class="btn">
                  <edit
                    @click="editReportItem(item, 'todayPlanReportList')"
                    class="icon"
                  />
                </div>
                <span class="split_char"></span>
                <div class="btn">
                  <delete
                    @click="deleteReportItem(item, 'todayPlanReportList')"
                    class="icon"
                  />
                </div>
              </div>
            </template>
            <div class="report_cell_item">
              <span class="nowrap">{{ i + 1 }}、</span>
              <div class="f_1">
                <span>{{ item.reportText }}</span>
                <span v-if="Number(item.workProgress)" class="nowrap ml_s">
                  {{ item.workProgress }}%
                </span>
                <span class="nowrap ml_s"> —— {{ item.reportName }} </span>
              </div>
              <!-- <div
                v-if="deleteBtnVisible"
                class="delete_btn"
                @click="deleteReportItem(item, 'today')"
              >
                <delete-filled
                  style="
                    width: 1.2em;
                    height: 1.2em;
                    margin-right: 14px;
                    color: #f56c6c;
                  "
                />
              </div> -->
            </div>
          </el-tooltip>
        </div>
      </div>
    </div>
    <div v-else class="empty_box">无</div>

    <div v-if="reasonVisible">
      <div class="report_cell_title" :style="{ 'background-color': titleBg }">
        上个工作日问题反馈
      </div>

      <div v-if="reportCommitRemark" class="input_remark_box">
        <span>{{ reportCommitRemark }}</span>
      </div>
      <div v-else class="empty_box">无</div>
    </div>

    <!-- 修改发送日报弹框 -->
    <ReportCommitFormEditDialog
      ref="reportCommitFormEditDialog"
      @confirm="editConfirm"
    />
  </div>
</template>

<script>
import { reactive, watch, computed, ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { copyInClip } from "../../../utils/common";
import { cloneDeep } from "lodash";
import ReportCommitFormEditDialog from "./ReportCommitFormEditDialog.vue";

export default {
  name: "ReportCommitList",
  components: {
    ReportCommitFormEditDialog,
  },
  props: {
    // 上个工作日完成的日报列表
    lastFinishReportList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // 今日工作计划的日报列表
    todayPlanReportList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    // 上个工作日问题反馈
    reportCommitRemark: {
      type: String,
      default: "",
    },
    // 日报没有模块时的显示类别名称
    otherModuleKey: {
      type: String,
      default: "【其他】",
    },
    // 标题背景色
    titleBg: {
      type: String,
      default: "#faecd8",
    },
    // 是否显示上个工作日问题反馈（默认显示）
    reasonVisible: {
      type: Boolean,
      default: true,
    },
    // 是否显示删除按钮（默认不显示）
    deleteBtnVisible: {
      type: Boolean,
      default: false,
    },
    // 是否显示新增按钮（默认不显示）
    createBtnVisible: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, context) {
    const reportData = reactive({
      lastFinishReportList: [],
      todayPlanReportList: [],
    });

    const getModuleDisplayName = (row) => {
      if (!row.moduleNames) {
        return "";
      }
      let nameStr = "";
      const nameArr = row.moduleNames.split("|").filter((cell) => cell);
      nameArr.forEach((item) => {
        nameStr += `【${item}】`;
      });
      return nameStr;
    };

    const getSortReportObj = (list) => {
      const reportObj = {};
      list.forEach((item) => {
        const nameStr = getModuleDisplayName(item);
        if (nameStr) {
          if (reportObj[nameStr]) {
            reportObj[nameStr].push(item);
          } else {
            const list = [];
            list.push(item);
            reportObj[nameStr] = list;
          }
        } else {
          if (reportObj[props.otherModuleKey]) {
            reportObj[props.otherModuleKey].push(item);
          } else {
            const list = [];
            list.push(item);
            reportObj[props.otherModuleKey] = list;
          }
        }
      });
      Object.keys(reportObj).forEach((key) => {
        reportObj[key].sort((a, b) => {
          const am = a.reportName;
          const bm = b.reportName;
          return am.localeCompare(bm);
        });
      });
      return reportObj;
    };

    const dealReportContent = (list, content) => {
      const reportObj = getSortReportObj(list);
      // console.log("reportObj ==>", reportObj);
      Object.keys(reportObj).forEach((key) => {
        if (key !== props.otherModuleKey) {
          content += "\n" + key + "\n";
          reportObj[key].forEach((cell, index) => {
            content += index + 1;
            content += cell.splitChar;
            content += cell.reportText + "  ";
            if (Number(cell.workProgress)) {
              content += `${cell.workProgress}%  `;
            }
            content += ` —— ${cell.reportName}`;
            content += "\n";
          });
        }
      });
      if (reportObj[props.otherModuleKey]) {
        content += "\n" + props.otherModuleKey + "\n";
        reportObj[props.otherModuleKey].forEach((cell, index) => {
          content += index + 1;
          content += cell.splitChar;
          content += cell.reportText + "  ";
          if (Number(cell.workProgress)) {
            content += `${cell.workProgress}%  `;
          }
          content += ` —— ${cell.reportName}`;
          content += "\n";
        });
      }
      return content;
    };

    // 复制
    const copyData = (row) => {
      let content = "";
      // 上个工作日完成
      if (row.lastFinishReportList.length) {
        content +=
          `①上个工作日完成（${row.lastFinishReportList[0].reportTime}）` + "\n";
        content = dealReportContent(row.lastFinishReportList, content);
      } else {
        content += `①上个工作日完成` + "\n";
        content += "无" + "\n";
      }
      // 今日工作计划
      content +=
        "\n" +
        `②今日工作计划（${row.todayPlanReportList[0].reportTime}）` +
        "\n";
      content = dealReportContent(row.todayPlanReportList, content);
      // 上个工作日问题反馈
      content += "\n" + `③上个工作日问题反馈` + "\n";
      if (row.reportCommitRemark) {
        content += row.reportCommitRemark + "\n";
      } else {
        content += "无" + "\n";
      }
      copyInClip(content);
    };

    // 通用行合并函数（将相同多列数据合并为一行）
    const mergeRowMethod = ({ row, _rowIndex, column, visibleData }) => {
      const fields = ["moduleNames"];
      const cellValue = row[column.property];
      if (cellValue && fields.includes(column.property)) {
        const prevRow = visibleData[_rowIndex - 1];
        let nextRow = visibleData[_rowIndex + 1];
        if (prevRow && prevRow[column.property] === cellValue) {
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = visibleData[++countRowspan + _rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    };

    const editReportItem = (row, type) => {
      reportCommitFormEditDialog.value &&
        reportCommitFormEditDialog.value.open(row, type);
    };

    const deleteReportItem = (row, type) => {
      ElMessageBox.confirm(
        `确定要删除${row.reportName ? "【" + row.reportName + "】的" : ""}【${
          row.reportText.length > 10
            ? row.reportText.slice(0, 10) + "..."
            : row.reportText
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          let index = -1;
          switch (type) {
            case "lastFinishReportList":
              if (row.id) {
                index = reportData.lastFinishReportList.findIndex(
                  (item) => item.id === row.id
                );
              } else {
                index = reportData.lastFinishReportList.findIndex(
                  (item) => JSON.stringify(item) === JSON.stringify(row)
                );
              }
              if (index !== -1) {
                reportData.lastFinishReportList.splice(index, 1);
              }
              break;
            case "todayPlanReportList":
              if (reportData.todayPlanReportList.length <= 1) {
                return ElMessage.warning("今日工作计划至少为一条");
              }
              if (row.id) {
                index = reportData.todayPlanReportList.findIndex(
                  (item) => item.id === row.id
                );
              } else {
                index = reportData.todayPlanReportList.findIndex(
                  (item) => JSON.stringify(item) === JSON.stringify(row)
                );
              }
              if (index !== -1) {
                reportData.todayPlanReportList.splice(index, 1);
              }
              break;
          }
          changeParentData({
            lastFinishReportList: reportData.lastFinishReportList,
            todayPlanReportList: reportData.todayPlanReportList,
          });
        })
        .catch(() => {});
    };

    // 获取数据
    const getListData = () => {
      return {
        lastFinishReportList: reportData.lastFinishReportList,
        todayPlanReportList: reportData.todayPlanReportList,
      };
    };

    const createReport = (type) => {
      reportCommitFormEditDialog.value &&
        reportCommitFormEditDialog.value.open(null, type);
    };

    /**
     * 监听属性
     */
    watch(
      () => props.lastFinishReportList,
      (newVal) => {
        // console.log("watch ===> props.lastFinishReportList", newVal);
        reportData.lastFinishReportList = cloneDeep(props.lastFinishReportList);
      },
      {
        deep: true,
        immediate: true,
      }
    );
    watch(
      () => props.todayPlanReportList,
      (newVal) => {
        // console.log("watch ===> props.todayPlanReportList", newVal);
        reportData.todayPlanReportList = cloneDeep(props.todayPlanReportList);
      },
      {
        deep: true,
        immediate: true,
      }
    );

    /**
     * 计算属性
     */
    const lastFinishReportObj = computed(() => {
      return getSortReportObj(reportData.lastFinishReportList);
    });
    const todayPlanReportObj = computed(() => {
      return getSortReportObj(reportData.todayPlanReportList);
    });

    // ------------------- 修改发送日报弹框 start -----------------------------------
    const reportCommitFormEditDialog = ref(null);

    const editConfirm = (data, type, oldReport) => {
      let row;
      if (oldReport) {
        let index = -1;
        switch (type) {
          case "lastFinishReportList":
            if (data.id) {
              index = reportData.lastFinishReportList.findIndex(
                (item) => item.id === data.id
              );
            } else {
              index = reportData.lastFinishReportList.findIndex(
                (item) => JSON.stringify(item) === JSON.stringify(oldReport)
              );
            }
            row = reportData.lastFinishReportList[index];
            break;
          case "todayPlanReportList":
            if (data.id) {
              index = reportData.todayPlanReportList.findIndex(
                (item) => item.id === data.id
              );
            } else {
              index = reportData.todayPlanReportList.findIndex(
                (item) => JSON.stringify(item) === JSON.stringify(oldReport)
              );
            }
            row = reportData.todayPlanReportList[index];
            break;
        }
        if (row) {
          Object.keys(data).forEach((key) => {
            row[key] = data[key];
          });
        }
      } else {
        switch (type) {
          case "lastFinishReportList":
            reportData.lastFinishReportList.push(data);
            break;
          case "todayPlanReportList":
            reportData.todayPlanReportList.push(data);
            break;
        }
      }
      // console.log(
      //   "reportData.lastFinishReportList ",
      //   reportData.lastFinishReportList
      // );
      // console.log(
      //   "reportData.todayPlanReportList ",
      //   reportData.todayPlanReportList
      // );
      changeParentData({
        lastFinishReportList: reportData.lastFinishReportList,
        todayPlanReportList: reportData.todayPlanReportList,
      });
    };

    const changeParentData = ({
      lastFinishReportList,
      todayPlanReportList,
    }) => {
      context.emit("changeReportData", {
        lastFinishReportList,
        todayPlanReportList,
      });
    };

    // ------------------- 修改发送日报弹框 end -----------------------------------

    return {
      reportData,
      lastFinishReportObj,
      todayPlanReportObj,
      reportCommitFormEditDialog,
      copyData,
      mergeRowMethod,
      deleteReportItem,
      editReportItem,
      editConfirm,
      createReport,
    };
  },
};
</script>

<style lang="less" scoped>
.component_container {
  .report_cell_title {
    font-size: 16px;
    padding: 10px 20px;
    // background-image: linear-gradient(to right top, #ec008c, #6739b6);
    // background-color: #faecd8;
    background-color: #f2f6fc;
    color: #303133;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .time_text {
      font-size: 14px;
      font-weight: 400;
      color: #999;
    }
  }
  .report_content_part {
    background-color: #fff;
    .report_part_title {
      padding: 10px 20px;
      line-height: 20px;
      color: #333;
      font-size: 16px;
    }
  }

  .report_cell_content {
    .report_cell_item {
      padding: 10px 20px;
      display: flex;
      line-height: 20px;
      // border-bottom: 1px solid #ebeef5;
      position: relative;
      color: #333;
      font-size: 15px;
      white-space: normal;
      &:hover {
        background-color: #f2f2f2;
        .delete_btn {
          display: block;
        }
      }
      &:last-child {
        border: 0;
      }
    }
    .delete_btn {
      position: absolute;
      right: 0px;
      top: 50%;
      transform: translateY(-44%);
      // display: none;
      cursor: pointer;
      z-index: 10;
    }
  }

  .empty_box {
    color: #999;
    padding: 10px 20px;
    background-color: #fff;
  }

  .input_remark_box {
    padding: 10px 20px;
    background-color: #fff;
    word-break: keep-all;
    white-space: pre-wrap; // 保留空白符序列，但是正常地进行换行
    line-height: 26px;
    color: #333;
    font-size: 16px;
  }
}
</style>
<style lang="less">
.report_commit_list_cell_control_box {
  white-space: nowrap;
  .split_char {
    width: 1px;
    height: 14px;
    background-color: #ccc;
    margin: 0 10px;
    display: inline-block;
  }
  .btn {
    display: inline-block;
    position: relative;
    .icon {
      width: 20px;
      height: 20px;
      color: #fff;
      cursor: pointer;
    }
  }
}
</style>
